package com.bootdo.clouddo.controller.user;


import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.bootdo.clouddo.controller.common.CommonController;
import com.bootdo.clouddo.domain.user.QaUsers;
import com.bootdo.clouddo.domain.user.vo.QaUsersVo;
import com.bootdo.clouddo.service.user.WxService;
import com.bootdo.clouddo.utils.R;
import com.bootdo.clouddo.utils.StringUtils;
import com.bootdo.clouddo.utils.common.ErrorCode;
import com.bootdo.clouddo.utils.spring.MD5SaltPasswordEncoder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class QaUserController extends CommonController {

    @Autowired
    @Qualifier("encoder")
    private MD5SaltPasswordEncoder encoder;

    @Autowired
    private WxService wxService;

    @RequestMapping("/currentUser")
    public R getCurrentUser(HttpServletRequest request) {
    	QaUsers user = userService.findById(getUid());
    	if(user == null)
    		return R.error();
    	return R.data(user.toVo());
    }

    /**
     * 更新用户基本信息（微信信息）
     * @return
     */
    @RequestMapping(value="/updateUserWxInfo", method = RequestMethod.POST)
    public R updateUserWxInfo(@RequestBody Map<String, String> params, HttpServletRequest request){
        try{
            QaUsers user = getCurrentLoginedUser(request);
            String sessionKey = user.getWxSessionKey();
            String encryptedData = params.get("ed");
            String iv = params.get("iv");
            // 校验参数完整性
            if(StringUtils.isEmpty(encryptedData) || StringUtils.isEmpty(iv))
                return R.error("invalid_parameters");
			System.out.println("updateUserWxInfo: " + sessionKey);
            // 解密参数
            WxMaUserInfo wxUserInfo = wxService.getUserInfo(sessionKey, encryptedData, iv);
            if(wxUserInfo == null)
                return R.error("decryption_failure");
            // 更新用户信息
            userService.updateUserWxInfoById(user, wxUserInfo);
            // 获取最新用户信息
            user = userService.findById(user.getUid());
            return R.data(user.toVo());
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.error();
    }

	/**
	 * 更新用户手机号码
	 * @return
	 */
	@RequestMapping(value="/updateUserMobile", method = RequestMethod.POST)
	public R updateUserMobile(@RequestBody Map<String, String> params, HttpServletRequest request){
		try{
			QaUsers user = getCurrentLoginedUser();
			String encryptedData = params.get("ed");
			String iv = params.get("iv");
			// 校验参数完整性
			if(StringUtils.isEmpty(encryptedData) || StringUtils.isEmpty(iv))
				return R.error("invalid_parameters");
			// System.out.println("开始解密，SessionKey：" + user.getWxSessionKey());
			// 解密参数
			WxMaPhoneNumberInfo phontInfo = wxService.getUserPhone(user.getWxSessionKey(), encryptedData, iv);
			if(phontInfo == null)
				return R.error("decryption_failure");
			if(userService.existsByMobile(phontInfo.getPhoneNumber()))
				return R.error(ErrorCode.MOBILE_ALREADY_EXISTS);
			// 更新用户信息
			userService.updateUserMobileoById(user, phontInfo);
			// 获取最新用户信息
			user = userService.findById(user.getUid());
			QaUsersVo userVo = new QaUsersVo();
			// 更新至缓存
			BeanUtils.copyProperties(user, userVo);
			// 更新redis用户缓存
			refreshTokenUser(request, user);
			return R.data(userVo);
		}catch (Exception e){
			e.printStackTrace();
		}
		return R.error();
	}
    
	/**
	 * 判断该用户是否注册
	 * @return	false 未注册；true 已注册
	 */
	@RequestMapping("/checkUserMobileExisting/{mobile}")
    public R checkUserMobileExisting(@PathVariable String mobile) {
		try {
			QaUsers user =  userService.findByMobile(mobile);
			return R.data(user != null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.error();
    }
    
    /**
	 * 判断该用户是否注册
	 * @return	false 未注册；true 已注册
	 */
	@RequestMapping("/checkUserNameExisting/{userName}")
    public R checkUserNameExisting(@PathVariable String userName) {
		try {
			QaUsers user =  userService.selectByUserName(userName);
			return R.data(user != null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.error();
    }

//    @RequestMapping(value="/tag/add", method=RequestMethod.POST)
//    public R addTag(String tag) {
//    	try {
//    		if(StringUtils.isBlank(tag))
//    			return R.error("tag_cant_be_empty");
//    		Long uid = getUid();
//    		List<QaUsersTag> oldTags = tagService.findByUid(uid);
//    		if(oldTags == null || oldTags.isEmpty())
//    			return R.data(tagService.save(uid, tag));
//    		for (QaUsersTag t : oldTags) {
//				if(StringUtils.equals(t.getText(), tag))
//					return R.error("tag_already_exists");
//			}
//    		return R.data(tagService.save(uid, tag));
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//    	return R.error();
//    }
//
//    @RequestMapping("/tag/delete/{tagId}")
//    public R deleteTag(@PathVariable Long tagId) {
//    	try {
//    		if(tagService.deleteByTagIdAndUid(getUid(), tagId) > 0)
//    			return R.ok();
//    		return R.error("tag_not_exists");
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//    	return R.error();
//    }
}
